package com.ctshk.rpc.order.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.OrderCollectionStatus;
import com.ctshk.common.enums.SystemBusinessType;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.rpc.finance.req.bill.BillOperateRefundReq;
import com.ctshk.rpc.finance.service.IFinanceBillService;
import com.ctshk.rpc.order.goods.entity.Commodity;
import com.ctshk.rpc.order.goods.entity.OrderCommodity;
import com.ctshk.rpc.order.goods.entity.OrderCommodityCollection;
import com.ctshk.rpc.order.goods.mapper.CommodityMapper;
import com.ctshk.rpc.order.goods.mapper.OrderCommodityCollectionMapper;
import com.ctshk.rpc.order.goods.mapper.OrderCommodityMapper;
import com.ctshk.rpc.order.goods.service.IOrderCommodityCollectionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 商品订单收款明细 服务实现类
 * </p>
 *
 * @author 姜斌文
 * @since 2021-04-19
 */
@Slf4j
@DubboService
public class OrderCommodityCollectionServiceImpl extends ServiceImpl<OrderCommodityCollectionMapper, OrderCommodityCollection> implements IOrderCommodityCollectionService {

    @Autowired
    private OrderCommodityCollectionMapper orderCommodityCollectionMapper;

    @Autowired
    private CommodityMapper commodityMapper;

    @Autowired
    private OrderCommodityMapper orderCommodityMapper;

    @DubboReference
    private IFinanceBillService iFinanceBillService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result reconfirm(Long id, Long userId) {
        OrderCommodityCollection orderCommodityCollection = orderCommodityCollectionMapper.selectCollectionById(id);
        if (null == orderCommodityCollection) {
            // 收款记录不存在
            log.info("【收款记录-再次确认-收款记录不存在】");
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23039);
        }
        if (orderCommodityCollection.getStatus() == null || orderCommodityCollection.getStatus() != OrderCollectionStatus.REJECT.getCode()) {
            // 收款记录的状态必须是驳回，才能再次确认
            log.info("【收款记录-再次确认-收款记录的状态必须是驳回，才能再次确认】");
            throw new BusinessException(SystemError.MALL_MERCHANDISE_23040);
        }
        orderCommodityCollection.setStatus(OrderCollectionStatus.UN_REJECT.getCode());
        orderCommodityCollection.setRejectInfo("");
        orderCommodityCollection.setModifiedId(userId);
        orderCommodityCollection.setGmtModified(LocalDateTime.now());
        orderCommodityCollectionMapper.updateCommodityCollectionById(orderCommodityCollection);

        // 再次确认对接财务中心
        reconfirmToFinance(orderCommodityCollection, userId);
        return Result.success();
    }

    @Override
    public Result queryCollectionAmount(Long orderId, Long userId) {
        // 查询商品信息
        OrderCommodity orderCommoditie = orderCommodityMapper.selectByOrderId(orderId);
        log.info("【中旅到家--取消订单--查询退款金额--查询商品信息】，返参为:{}", JSON.toJSONString(orderCommoditie));
        if (null == orderCommoditie) {
            return Result.failed(SystemError.MALL_MERCHANDISE_23000);
        }
        BigDecimal count = new BigDecimal("0");
//        List<BigDecimal> amountList = new ArrayList<>();
        // 计算退改手续费(产品说按商品中最贵的手续费扣，有事找产品)
//        for (OrderCommodity orderCommodity : orderCommodities) {
        BigDecimal amount = new BigDecimal("0");  // 总金额
        Commodity commodity = commodityMapper.selectCommodityById(orderCommoditie.getCommodityId().toString());
        // 加数值
        if (commodity.getRefundServiceChargeType() == 1) {
            amount = amount.add(commodity.getRefundServiceCharge());
        }
        // 加百分比
        else if (commodity.getRefundServiceChargeType() == 2) {
            BigDecimal percentage = commodity.getRefundServiceCharge().divide(new BigDecimal("100"));
            amount = amount.add(orderCommoditie.getCommodityTotalPrice().multiply(percentage));
        }
        count = count.add(orderCommoditie.getCommodityTotalPrice());
//        amountList.add(amount);
//        }
        // 拿到最大值
//        BigDecimal max = Collections.max(amountList);
        // 查询商品收款记录
//        List<OrderCommodityCollection> orderCommodityCollectionList = orderCommodityCollectionMapper.selectCollectionByOrderId(orderId);
//        log.info("【中旅到家--取消订单--查询退款金额--查询商品收款记录】，返参为:{}", JSON.toJSONString(orderCommodityCollectionList));
//        if (CollectionUtils.isEmpty(orderCommodityCollectionList)) {
//            return Result.failed(SystemError.MALL_MERCHANDISE_23039);
//        }
//        BigDecimal count = new BigDecimal("0");
//        for (OrderCommodityCollection commodityCollection : orderCommodityCollectionList) {
//            count = count.add(commodityCollection.getCollectionAmount());
//        }
        count = count.subtract(amount); // 减去手续费后的金额
        log.info("【中旅到家--取消订单--查询退款金额】，退款金额为：{}", count);
        return Result.success(count);
    }

    /**
     * 再次确认收款对接财务中心
     *
     * @param commodityCollection
     * @param userId
     */
    private void reconfirmToFinance(OrderCommodityCollection commodityCollection, Long userId) {
        BillOperateRefundReq req = new BillOperateRefundReq();
        // 收款单号
        req.setBillNumber(commodityCollection.getCollectionNumber());
        // 业务类型
        req.setBusinessType(SystemBusinessType.COMMODITY.getCode());
        // 用户id
        req.setUserId(userId);
        iFinanceBillService.reConfirm(req);
    }
}
